package com.ws.lv.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ws.lv.bean.*;
import com.ws.lv.service.Acl_permissionService;
import com.ws.lv.service.Acl_roleService;
import com.ws.lv.service.Acl_userService;
import com.ws.lv.service.SupplierService;
import com.ws.lv.util.Res;
import com.ws.lv.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/acl_user")
public class Acl_userController {
    
    @Autowired
    Acl_userService acl_userService;
    @Autowired
    SupplierService supplierService;
    @Autowired
    Acl_roleService acl_roleService;
    @Autowired
    Acl_permissionService acl_permissionService;

    //去用户管理页面 查询用户
    @RequestMapping("/selectAcl_user")
    public String selectAcl_user() {
        System.out.println("跳转到用户管理页面");
        return "adminpage/acl_user/list";
    }


    //去后台登录页
    @RequestMapping("/toLogin")
    public String toLogin() {
        System.out.println("跳转到后台登录页");
        return "adminpage/login";
    }


    //登录功能
    @RequestMapping("/selectAcl_userByLogin")
    public String selectAcl_userByLogin(Acl_user acl_user, HttpServletRequest request) {
        System.out.println("登录功能");
        Acl_user aclUser = acl_userService.selectAcl_userByUsername(acl_user.getUsername());
        if (aclUser != null){
            boolean verify = SecurityUtils.verify(acl_user.getPassword(),aclUser.getPassword());
            if (verify){
                System.out.println("登录成功");
                //获取用户拥有的角色
                Set<String> permissions = new HashSet<>();
                List<Acl_role> aclRoles = acl_roleService.selectAcl_rolesByUserId(aclUser.getUser_id());
                for (Acl_role aclRole : aclRoles){
                    List<Acl_role_permission> acl_role_permissions = acl_roleService.selectAcl_role_permissionByRoleId(aclRole.getRole_id());
                    if (acl_role_permissions != null){
                        for (Acl_role_permission acl_role_permission : acl_role_permissions){
                            Acl_permission acl_permission = acl_permissionService.selectAcl_permissionById(acl_role_permission.getPerm_id());
                            if (acl_permission != null){
                                permissions.add(acl_permission.getPath());
                            }
                        }
                    }
                }
                request.getSession().setAttribute("aclUser",aclUser);
                request.getSession().setAttribute("permissions",permissions);
                return "forward:/adminpage/toAdminPage";
            }
        }
        return "redirect:/acl_user/toLogin";
    }

    //退出登录
    @RequestMapping("/outLogin")
    public String outLogin(HttpServletRequest request){
        System.out.println("退出登录");
        request.getSession().removeAttribute("aclUser");
        request.getSession().removeAttribute("permissions");
        return "redirect:/acl_user/toLogin";
    }

    //多条件分页查询用户
    @RequestMapping("/selectAcl_users")
    public String selectAcl_users(Model model, String username, Integer is_deleted, Integer sid, Integer currentPage) {
        System.out.println("进入查询用户");
        List<Supplier> suppliers = supplierService.selectSupplierAll();
        model.addAttribute("suppliers", suppliers);
        model.addAttribute("username", username);
        model.addAttribute("is_deleted", is_deleted);
        model.addAttribute("sid", sid);
        PageHelper pageHelper = new PageHelper();//分页帮助类
        if (currentPage == null){
            pageHelper.startPage(1, 5);
        }else {
            pageHelper.startPage(currentPage, 5);
        }
        List<Acl_user> acl_users = acl_userService.selectAcl_users(username, is_deleted, sid);
        PageInfo pageInfo = new PageInfo(acl_users);
        model.addAttribute("pageInfo", pageInfo);

        return "adminpage/acl_user/list";
    }

    //去增加页面
    @RequestMapping("/toInsertAcl_user")
    public String toInsertAcl_user(Model model) {
        System.out.println("去增加页面");
        List<Supplier> suppliers = supplierService.selectSupplierAll();
        model.addAttribute("suppliers",suppliers);
        return "adminpage/acl_user/add";
    }

    //增加用户
    @RequestMapping("/insertAcl_user")
    public String insertAcl_user(Acl_user acl_user, MultipartFile image) {
        System.out.println("增加用户页面");
        System.out.println(acl_user);
        try {
            Acl_user aclUser = acl_userService.selectAcl_userByUsername(acl_user.getUsername());
            if (aclUser == null){
                if (image.getSize() > 0){
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    String suffix = image.getOriginalFilename().split("\\.")[1];
                    acl_user.setUser_tx(uuid+"."+suffix);
                    acl_user.setPassword(SecurityUtils.encrypt(acl_user.getPassword()));
                    image.transferTo(new File(Res.adminTxFileDir+uuid+"."+suffix));
                    int i = acl_userService.insertAcl_user(acl_user);
                    return "redirect:/acl_user/selectAcl_users";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/acl_user/toInsertAcl_user";
    }

    //逻辑删除用户
    @RequestMapping("/softUpdateAcl_user")
    public String softUpdateAcl_user(Integer user_id){
        System.out.println("逻辑删除用户");
        int i = acl_userService.softUpdateAcl_user(user_id);
        return "redirect:/acl_user/selectAcl_users";
    }

    //去修改用户信息页面
    @RequestMapping("/toUpdateAcl_user")
    public String toUpdateAcl_user(Integer user_id, Model model) {
        System.out.println("去修改用户信息页面");
        Acl_user acl_user = acl_userService.selectAcl_userById(user_id);
        model.addAttribute("acl_user",acl_user);
        List<Supplier> suppliers = supplierService.selectSupplierAll();
        model.addAttribute("suppliers",suppliers);
        return "adminpage/acl_user/update";
    }


    //修改用户信息
    @RequestMapping("/updateAcl_user")
    public String updateAcl_user(Acl_user acl_user, MultipartFile image) throws IOException {
        System.out.println("修改用户信息");
        try {
            Acl_user newAcl_User = acl_userService.selectAcl_userByUsername(acl_user.getUsername());
            if (newAcl_User == null){
                if (image.getSize() > 0){
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    String suffix = image.getOriginalFilename().split("\\.")[1];
                    acl_user.setUser_tx(uuid+"."+suffix);
                    image.transferTo(new File(Res.adminTxFileDir+uuid+"."+suffix));
                    //删除原头像
                    File file = new File(Res.adminTxFileDir+newAcl_User.getUser_tx());
                    if (file.exists()){
                        file.delete();
                        System.out.println("删除原头像");
                    }
                    System.out.println("更换新头像");
                }else {
                    System.out.println("使用原头像");
                    System.out.println(acl_user.getUser_tx());
                }
            }else {
                if (acl_user.getUser_id() == newAcl_User.getUser_id()){
                    System.out.println("只更换头像");
                    if (image.getSize() > 0){
                        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                        String suffix = image.getOriginalFilename().split("\\.")[1];
                        acl_user.setUser_tx(uuid+"."+suffix);
                        image.transferTo(new File(Res.adminTxFileDir+uuid+"."+suffix));
                        //删除原头像
                        File file = new File(Res.adminTxFileDir+newAcl_User.getUser_tx());
                        if (file.exists()){
                            file.delete();
                            System.out.println("删除原头像2");
                        }
                        System.out.println("更换新头像2");
                    }else {
                        System.out.println("使用原头像2");
                        System.out.println(acl_user.getUser_tx());
                    }
                }else {
                    return "redirect:/acl_user/toUpdateAcl_user?user_id="+acl_user.getUser_id();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }


        System.out.println(acl_user);
        int i = acl_userService.updateAcl_user(acl_user);
        return "redirect:/acl_user/selectAcl_users";
    }

    //批量删除用户
    @RequestMapping("/deleteAcl_users")
    public String deleteAcl_users(String user_ids) {
        System.out.println("批量删除用户");
        if (user_ids!=null){
            String[] split = user_ids.split(",");
            ArrayList<Integer> list = new ArrayList<>();
            for (String s : split) {
                list.add(Integer.parseInt(s));
            }

            for (Integer id : list){
                Acl_user aclUser = acl_userService.selectAcl_userById(id);
                File file = new File(Res.adminTxFileDir+aclUser.getUser_tx());
                if (file.exists()){
                    file.delete();
                }
            }
            int i = acl_userService.deleteAcl_users(list);
        }
        return "redirect:/acl_user/selectAcl_users";
    }
    

    //重置密码
    @RequestMapping("/updateAcl_userPassword")
    public String updateAcl_userPassword(Integer user_id) {
        System.out.println("重置密码");
        String newPass = SecurityUtils.encrypt("123456");
        int i = acl_userService.updateAcl_userPassword(user_id,newPass);
        return "redirect:/acl_user/selectAcl_users";
    }

    //去分配角色页面
    @RequestMapping("/selectAcl_roleAll")
    public String selectAcl_roleAll(Model model,Integer user_id) {
        System.out.println("去分配角色页面");
        List<Acl_role> acl_roles = acl_roleService.selectAcl_roleAll();
        List<Acl_role> acl_rolesByUserId = acl_roleService.selectAcl_rolesByUserId(user_id);
        for (Acl_role acl_role : acl_roles){
            for (Acl_role acl_role2 : acl_rolesByUserId){
                if (acl_role.getRole_id().equals(acl_role2.getRole_id())){
                    acl_role.setChecked(true);
                    System.out.println(acl_role);
                }
            }
        }
        model.addAttribute("acl_roles",acl_roles);
        model.addAttribute("user_id",user_id);
        return "adminpage/acl_user/role";
    }

    //分配角色
    @RequestMapping("/insertAcl_user_role")
    public String insertAcl_user_role(Integer user_id,String role_ids,Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("分配角色");
        if (role_ids!=null && role_ids.trim().length() > 0){
            String[] split = role_ids.split(",");
            ArrayList<Integer> list = new ArrayList<>();
            for (String s : split) {
                list.add(Integer.parseInt(s));
            }
            //删除身份
            acl_userService.deleteAcl_user_role(user_id);
            //增加身份
            for (Integer role_id : list){
                int i = acl_userService.insertAcl_user_role(user_id,role_id);
            }
        }else {
            //删除身份
            acl_userService.deleteAcl_user_role(user_id);
        }
        Acl_user aclUser = (Acl_user) request.getSession().getAttribute("aclUser");
        if (aclUser != null){
            if (aclUser.getUser_id().equals(user_id)){
                PrintWriter writer = response.getWriter();
                writer.write("<script>window.parent.location.href='"+request.getContextPath()+"/acl_user/outLogin'</script>");
                writer.close();
            }
        }
        return "redirect:/acl_user/selectAcl_users";


    }



    


}
